//
//  EditPhoneViewController.m
//  cliqset
//
//  Created by David Hinson on 2/17/09.
//  Copyright 2009 Cliqset, Inc.. All rights reserved.
//

#import "EditPhoneViewController.h"
#import "cliqsetAppDelegate.h"
#import "Contact.h"

@implementation EditPhoneViewController

@synthesize phoneEdit;
@synthesize phoneTypeField;
@synthesize parent;
@synthesize phoneNumberField;
@synthesize valid;
@synthesize phoneNumber;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"Edit Phone";
	
	self.phoneEdit.backgroundColor = [UIColor clearColor];

	// Set save button
	UIBarButtonItem* saveButton = [[[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleBordered target:self action:@selector(doSave:)] retain];
	self.navigationItem.rightBarButtonItem = saveButton;

	// Set cancel button
	UIBarButtonItem* cancelButton = [[[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(doCancel:)] retain];
	self.navigationItem.leftBarButtonItem = cancelButton;
	
	// For our valid entries
	valid = [[NSMutableArray alloc] init];
	
	if (parent.isPersonal) {
		[valid addObject:@"home"];
		[valid addObject:@"mobile"];
		[valid addObject:@"fax"];
		//[valid addObject:@"pager"];
		//[valid addObject:@"other"];
	}
	else {
		[valid addObject:@"work"];
		[valid addObject:@"mobile"];
		[valid addObject:@"fax"];
		//[valid addObject:@"pager"];
		//[valid addObject:@"other"];
	}
}

// Do cancel
-(void)doCancel:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	[myApp slidePhoneOut];
}

// Do save
-(void)doSave:(id)id {
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	if ([self.phoneNumberField isEqualToString:@""]) {
		[myApp addTextToLog:@"Phone Number Cannot Be Empty!" withCaption:@"Edit Phone" ];
		return;
	}

	// Dereference our contact
	Contact *contact=nil; 
	if (self.parent.index >= 0) {
	if (parent.isFavorite) {
		for (int x=0; x<[myApp.contacts count]; x++) {
			Contact *localContact = (Contact*)[myApp.contacts objectAtIndex:x]; 
			if ([localContact.contactIdentifier isEqualToString:[myApp.favorites objectAtIndex:parent.index]]) {
				contact = localContact;
				break;
			}
		}
	} 
	else {
		contact = (Contact *)[myApp.contacts objectAtIndex:parent.index];
	}
	}
	else {
		contact = self.parent.bufferContact;
	}

	NSMutableString* strTag;
	if (parent.isPersonal) {
		strTag = (NSMutableString*)[@"" stringByAppendingFormat:@"%@", [[self.phoneTypeField capitalizedString] isEqualToString:@"Home"] ? @"Personal" : [self.phoneTypeField capitalizedString]];
		strTag = [strTag isEqualToString:@"Personal"] ? strTag : (NSMutableString*)[@"" stringByAppendingFormat:@"%@%@", @"Personal", strTag];
		}
	else {
		strTag = (NSMutableString*)[@"" stringByAppendingFormat:@"%@", [[self.phoneTypeField capitalizedString] isEqualToString:@"Office"] ? @"Work" : [self.phoneTypeField capitalizedString]];
		strTag = [strTag isEqualToString:@"Work"] ? strTag : (NSMutableString*)[@"" stringByAppendingFormat:@"%@%@", @"Work", strTag];
		}
	
	// Add through cliqset, if this is an update
	if (self.parent.index >= 0) {
		[myApp.cliqset putPhone:contact.contactIdentifier tag:strTag number:self.phoneNumberField primary:NO];
		}
	
	// And add back to contact phones array
	Phone * phone = [[Phone alloc] init];
	
	// Build phone entry
	phone.type        = strTag;
	phone.phoneNumber = self.phoneNumberField;
	phone.primary     = NO;
	
	// Cycle through phones... we need to remove any existing with the same type
	for (int x=0; x<[contact.phones count]; x++) {
		Phone * tp = (Phone*)[contact.phones objectAtIndex:x];
		if ([tp.type isEqualToString: strTag]) {
			[contact.phones removeObjectAtIndex:x];
			break;
			}
	}
	
	[contact.phones addObject:phone];
	[phone release];
	
	[myApp slidePhoneOut];
	[parent.contactDetailTable reloadData];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}

// Number of table sections
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 2;
}
	
// Return rows in table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	
	switch (section) {
		case 0:
			return 1.0;
			break;
			
		case 1:
			return 1.0;
			break;
			
		default:
			return 0;
			break;
	}
}

// Set row height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	switch (indexPath.section) {
		case 0:
			return 60.0;
			break;
		case 1:
			return 40.0;
			break;
		default:
			break;
	}
	
	return 0.0;
}

// Indicate disclosure
- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	if (indexPath.section == 1 && indexPath.row == 0) {
		return UITableViewCellAccessoryDisclosureIndicator;	
	} 
	else {
		return UITableViewCellAccessoryNone;
	}
}

// Draw cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	    
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
    [cell backgroundView].opaque=YES;
    [cell backgroundView].clearsContextBeforeDrawing;
   	[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

	UIFont* large_font      = [UIFont systemFontOfSize:18];
	UIFont* very_large_font = [UIFont systemFontOfSize:36];
	UIColor* textColor      = [UIColor colorWithRed:62.0/255.0 green:62.0/255.0 blue:62.0/255.0 alpha:1.0];
	
	cell.hidesAccessoryWhenEditing = NO;
	
	UILabel * phoneLabel      = [[UILabel alloc] initWithFrame:CGRectMake(20, 7, 290, 26)];
	
	if (phoneNumber) {[phoneNumber release];}
	
	phoneNumber = [[UITextField alloc] initWithFrame:CGRectMake(20,7,290,46)];

	switch (indexPath.section) {
		case 0:
			
			phoneNumber.textColor   = textColor;
			phoneNumber.font        = very_large_font;
			phoneNumber.placeholder = @"Phone";
			
			phoneNumber.keyboardType = UIKeyboardTypePhonePad;
			phoneNumber.autocapitalizationType = UITextAutocapitalizationTypeNone;
			[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(phoneNumberDidChange:) name:@"UITextFieldTextDidChangeNotification" object:phoneNumber];
			phoneNumber.text         = (!self.phoneNumberField || [self.phoneNumberField isEqualToString:@""]) ? @"" : self.phoneNumberField;
			
			[phoneNumber becomeFirstResponder];
			
			[cell addSubview:phoneNumber];
			
			break;
		case 1:
			
			phoneLabel.textColor                 = textColor;
			phoneLabel.font                      = large_font;
			phoneLabel.adjustsFontSizeToFitWidth = NO;
			
			phoneLabel.text                      = (!self.phoneTypeField || [self.phoneTypeField isEqualToString:@""]) ? @"mobile" : self.phoneTypeField;
			self.phoneTypeField                  = (NSMutableString*)phoneLabel.text;
			
			[cell addSubview:phoneLabel];
			break;
	}
	
	[phoneLabel release];
	
	//UIColor* myBGColor               = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
	//cell.backgroundView.backgroundColor = myBGColor;
	for ( UIView* view in cell.contentView.subviews ) 
	{
		view.backgroundColor = [ UIColor clearColor ];
	}
	
	return cell;
}	

// Our phone number changed... we want to format it as we go.
-(void)phoneNumberDidChange:(id)textField {	
	
	static BOOL bToggle = NO;
	
	if (bToggle == YES) {
		bToggle = NO;
		return;
	}
	
	bToggle = YES;
	
	UITextField *field              = [textField object];
	NSMutableString* strPhoneNumber = (NSMutableString*)[[textField object] text];

	strPhoneNumber = (NSMutableString*)[strPhoneNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
	strPhoneNumber = (NSMutableString*)[strPhoneNumber stringByReplacingOccurrencesOfString:@" " withString:@""];
	strPhoneNumber = (NSMutableString*)[strPhoneNumber stringByReplacingOccurrencesOfString:@"(" withString:@""];
	strPhoneNumber = (NSMutableString*)[strPhoneNumber stringByReplacingOccurrencesOfString:@")" withString:@""];

	NSMutableString* strDisplay = @"";

	strDisplay = strPhoneNumber;
	
	if ([strPhoneNumber length] && [[strPhoneNumber substringToIndex:1] isEqualToString:@"1"]) {
		// Strip 1
		strPhoneNumber = (NSMutableString*)[strPhoneNumber substringFromIndex:1];
		if ([strPhoneNumber length] == 3) {
			strDisplay = (NSMutableString*)[@"" stringByAppendingFormat:@"1 %@", [strPhoneNumber substringToIndex:3]];
		}
		if ([strPhoneNumber length] >= 4 && [strPhoneNumber length] <= 6) {
			strDisplay = (NSMutableString*)[@"" stringByAppendingFormat:@"1 (%@) %@", [strPhoneNumber substringToIndex:3], [strPhoneNumber substringFromIndex:3]];
		}
		if ([strPhoneNumber length] >= 7 && [strPhoneNumber length] <= 10) {
			strDisplay = (NSMutableString*)[@"" stringByAppendingFormat:@"1 (%@) %@-%@", [strPhoneNumber substringToIndex:3], [[strPhoneNumber substringFromIndex:3] substringToIndex:3], [strPhoneNumber substringFromIndex:6]];
		} 
		
		// Cleanup trailing '-'
		if (([strDisplay length] == 4) && [[strDisplay substringFromIndex:3] isEqualToString:@"-"]) {
			strDisplay = (NSMutableString*)[strDisplay stringByReplacingOccurrencesOfString:@"-" withString:@""];
		}
	} 
	else {
	
		if ([strPhoneNumber length] == 3) {
			strDisplay = (NSMutableString*)[@"" stringByAppendingFormat:@"%@-", [strPhoneNumber substringToIndex:3]];
			}
		if ([strPhoneNumber length] >= 4 && [strPhoneNumber length] <= 7) {
			strDisplay = (NSMutableString*)[@"" stringByAppendingFormat:@"%@-%@", [strPhoneNumber substringToIndex:3], [strPhoneNumber substringFromIndex:3]];
			}
		if ([strPhoneNumber length] >= 8 && [strPhoneNumber length] <= 10) {
			strDisplay = (NSMutableString*)[@"" stringByAppendingFormat:@"(%@) %@-%@", [strPhoneNumber substringToIndex:3], [[strPhoneNumber substringFromIndex:3] substringToIndex:3], [strPhoneNumber substringFromIndex:6]];
			} 
	
		// Cleanup trailing '-'
		if (([strDisplay length] == 4) && [[strDisplay substringFromIndex:3] isEqualToString:@"-"]) {
			strDisplay = (NSMutableString*)[strDisplay stringByReplacingOccurrencesOfString:@"-" withString:@""];
		}
	}
	
	NSLog(@"running...");
	
	field.text = strDisplay;	
	self.phoneNumberField = strDisplay;
}

// Row selected... 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	
	cliqsetAppDelegate* myApp = (cliqsetAppDelegate*)[[UIApplication sharedApplication] delegate];
	
	UITableViewCell *hitCell = [tableView cellForRowAtIndexPath:indexPath];	
    [hitCell setSelected:NO animated:YES];

	if (indexPath.section == 1) {
		[[NSNotificationCenter defaultCenter] removeObserver:self name:@"UITextFieldTextDidChangeNotification" object:phoneNumber];
		[myApp slidePhoneTypeIn:self];
		}
}

- (void)dealloc {
	[phoneNumber release];
	[valid release];
	[phoneNumberField release];
	[parent release];
	[phoneTypeField release];
	[phoneEdit release];
    [super dealloc];
}


@end
